<?php


namespace app\common\cachemodel;


use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;

class ZlcrAstrQuestionNote extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_astr_question_note';

    protected $cacheModel = 'astr_admin.question_note';

    public function saveData(array $saveData)
    {
        try
        {
            $res = $this->getQuestionNote($saveData['astr_id'], $saveData['qid']);
            if ($res)
            {   // 更新
                $data = [
                    'note' => $saveData['note'],
                    'update_time' => $saveData['time']
                ];
                $this->where('id', $res['id'])->update($data);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $saveData['qid'] . ':' . $saveData['astr_id'])->setCache($data);
            } else
            {   // 新增
                $this->save([
                    'qid' => (int)$saveData['qid'],
                    'astr_id' => (int)$saveData['astr_id'],
                    'note' => $saveData['note'],
                    'create_time' => $saveData['time']
                ]);
            }
        }
        catch (\Exception $e)
        {
            Log::write("占星师问题备注失败;错误信息：「{$e->getMessage()}」;错误文件「{$e->getFile()}」;行数「{$e->getLine()}」", true);
            return false;
        }

        return true;
    }

    /**
     * 获取问题备注信息
     * @param $astrId
     * @param $qid
     * @return array|mixed
     * @throws \Exception
     */
    public function getQuestionNote($astrId, $qid)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $qid . ':' . $astrId)
            ->getDataAndSet(function () use ($qid, $astrId)
            {
                try
                {
                    $notesData = $this->where(['qid' => $qid, 'astr_id' => $astrId])->field('id,note,create_time')->findOrFail()->toArray();
                }
                catch (\Exception $e)
                {
                    $notesData = [];
                }

                return $notesData;
            });
    }
}
